package com.atsmart.app.sql;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import com.atsmart.app.BizApp;
import com.atsmart.app.model.TemplateDetailInfo;
import com.atsmart.app.model.TemplateInfo;
import com.atsmart.app.model.TemplateListInfo;
import com.atsmart.app.utils.StringUtil;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Template;
/**
 * TODO 模板表
 */
public class TemplateDetailSql {

	private SQLiteDatabase db = null;

	/**
	 * 打开数据库
	 */
	public void open(SqlHelper dh) {
		// dh = new SqlHelper(null, "atsmart", null,SqlHelper.getDBVersion());
		db = dh.getWritableDatabase();
	}

	/* <string name="templateInfo">Create TABLE if not exists templateInfo( [_id] integer PRIMARY KEY
			    ASC AUTOINCREMENT, [templateInfos] text(2000), [temID] integer(5));</string>*/
	public synchronized void addTemplateInfo(TemplateDetailInfo at, int temId) {
		if (at == null) {
			return;
		}
		String strSql = "insert or replace into templateInfo (templateInfos,temID) values(?,?);";
		try {
			SQLiteStatement stm = db.compileStatement(strSql);
			String s = BizApp.getGson().toJson(at);
			stm.bindString(1, StringUtil.isEmptyOrNull(s) ? "" : s);
			stm.bindLong(2, temId);
			stm.execute();
			stm.clearBindings();
			stm.close();
		} catch (Exception e) {
			// will not happen
		}
	}

	public TemplateDetailInfo getTemplateInfo(int temID) {
		String sql = "";
		sql = " select _id,templateInfos,temID from templateInfo where temID=" + temID;
		 
		Cursor cursor = db.rawQuery(sql, null);
		TemplateDetailInfo historie = null;
		try {
			if (cursor != null && cursor.moveToFirst()) {
				String string = cursor.getString(1);
				Log.e("TAG", "string = " + string);
				historie = BizApp.getGson().fromJson(string, TemplateDetailInfo.class);
			}
		} catch (Exception e) {
			return null;
		} finally {
			cursor.close();
		}
		return historie;
	}
	 
	public int getCount(int temID) {
		String sql = "select _id,templateInfos,temID from templateInfo where temID=" + temID;
		Cursor cursor = db.rawQuery(sql, null);
		try {
			if (cursor != null && cursor.moveToFirst()) {
				return cursor.getCount();
			}
		} catch (Exception e) {
			return 0;
		} finally {
			cursor.close();
		}
		return 0;
	}
	 
	public void deleteAttribute(int temID) {
		// db.delete("position_attribute", null, null);
		db.execSQL("delete from templateInfo where temID="+ temID);
	}
	 
	public void delete() {
		// db.delete("position_attribute", null, null);
		db.execSQL("delete from templateInfo");
	}
}
